package com.gavindon.android.adapters

import android.view.KeyEvent
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import android.widget.Toast
import androidx.recyclerview.widget.RecyclerView
import com.gavindon.android.R

/**
 * description:
 * Created by liNan on  2022-1-25 10:44
 */
class TestRvAdapter : RecyclerView.Adapter<TestRvAdapter.ViewHolder>() {
    private val dataSource = listOf("首页", "游戏", "教育", "生活", "娱乐", "新闻", "直播", "我的")
    private var needFocus = true
    private var defaultFocus = 0

    inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        val tv = itemView.findViewById<TextView>(R.id.adapter_tv)
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val itemVIew =
            LayoutInflater.from(parent.context).inflate(R.layout.adapter_tv_test, parent, false)
        return ViewHolder(itemVIew)
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        holder.tv.setText(dataSource[position])

        holder.itemView.setOnFocusChangeListener { v, hasFocus ->
            if (hasFocus) {
                listener?.invoke(position)
            }
        }
        holder.itemView.setOnKeyListener { v, keyCode, event ->

            if (keyCode == KeyEvent.KEYCODE_DPAD_DOWN) {
                downListener?.invoke(position)
            }

            return@setOnKeyListener true
        }

        holder.itemView.isFocusable = true
        if (needFocus) {
            if (defaultFocus < 0) {
                defaultFocus = 0
            }
            if (defaultFocus >= itemCount) {
                defaultFocus = itemCount - 1
            }
            if (defaultFocus == position) {
                if (!holder.itemView.isFocusable) {
                    defaultFocus++
                } else {
                    holder.itemView.requestFocus()
                }
            }
        } else {
            //setNeedFocus(position == (getItemCount() - 1));
        }

    }

    override fun getItemCount() = dataSource.size

    var listener: ((Int) -> Unit)? = null
    fun setFocusChanged(e: (Int) -> Unit) {
        this.listener = e
    }

    var downListener: ((Int) -> Unit)? = null
    fun setDownFocusChanged(e: (Int) -> Unit) {
        this.downListener = e
    }

}